package sc.export
{
	import deng.fzip.FZip;
	import sc.*;
	import flash.events.Event;
	import flash.filesystem.*;
	
	
	public class BaseExport
	{
		protected var currentFile:File; // The currentFile opened (and saved) by the application
		protected var stream:FileStream = new FileStream(); // The FileStream object used for reading and writing the currentFile
		public var defaultDirectory:File; // The default directory
		
		public var ext:String = '.html';
		public var path:String  = "/";
		
		public function BaseExport()
		{
			defaultDirectory = File.documentsDirectory;
		}
		
		protected function saveTab(currFile:File, resTab:Resultrender, async:Boolean = true):void
		{
			resTab.rootPath = Export.path;
			resTab.reload();
			if (stream != null)	
			{
				stream.close();
			}
			stream = new FileStream();
			if(async)
				stream.openAsync(currFile, FileMode.WRITE);
			else
				stream.open(currFile, FileMode.WRITE);
			//stream.addEventListener(IOErrorEvent.IO_ERROR, writeIOErrorHandler);
			var str:String = resTab.d.htmlText;
			str = str.replace(/\r/g, "\n");
			str = str.replace(/\n/g, File.lineEnding);
			stream.writeUTFBytes(str);
			stream.close();
		}

		/**
		 * This saves the current tabs as a directory of HTML files
		 */
		public function saveDirOfHtml(currentDir:File):void 
		{
			var hell:texy_editor_tab = $.main.tabCont.selectedChild as  texy_editor_tab;
			var lim:uint = hell.output.numChildren;
			for(var i:uint = 0; i < lim; i++) {
				var resTab:Resultrender = hell.output.getChildAt(i) as Resultrender;
				currentFile = currentDir.resolvePath(resTab.path) as File;
				saveTab(currentFile, resTab);
			}
			currentFile = null;
		}
		
		public function saveSingleHtml(currFile:File):void
		{
			var hell:texy_editor_tab = $.main.tabCont.selectedChild as  texy_editor_tab;
			var resTab:Resultrender = hell.output.selectedChild as  Resultrender;
			saveTab(currFile, resTab);
			currentFile = null;
		}
		
		public function saveZipOfHtml(currFile:File):void 
		{
			var hell:texy_editor_tab = $.main.tabCont.selectedChild as  texy_editor_tab;
			var lim:uint = hell.output.numChildren;
			var zip:FZip = new FZip();
			for(var i:uint = 0; i < lim; i++) {
				var resTab:Resultrender = hell.output.getChildAt(i) as Resultrender;
				resTab.rootPath = Export.path;
				resTab.reload();
				var str:String = resTab.d.htmlText;
				str = str.replace(/\r/g, "\n");
				str = str.replace(/\n/g, File.lineEnding);
				zip.addFileFromString(resTab.path, str);
			}
			stream = new FileStream();
			stream.openAsync(currFile, FileMode.WRITE);
			zip.serialize(stream);
			stream.close();
			
		}

	}
}